from pymongo import MongoClient
import logging
import sys
import os


class MongoDBHandler(logging.Handler):

    def __init__(self, _id, log_db):
        logging.Handler.__init__(self)
        self.client = MongoClient()
        self.db = self.client['Experiment'][log_db]
        self._id = _id

    def emit(self, record):
        # Use default formatting:
        self.format(record)
        # print(type(record))
        # print(record.asctime, record.message, record.name)
        self.db.insert_one(
            {'exp_id': self._id, 'time': record.asctime, 'level': record.levelname, 'message': record.message})


def get_logger(name, log_db):
    DISABLE_MONGO = 'DISABLE_MONGO' in os.environ
    logFormatter = logging.Formatter("%(asctime)s [%(levelname)-5.5s]  %(message)s")
    rootLogger = logging.getLogger(str(name))

    #     fileHandler = logging.FileHandler("{0}/{1}.log".format('/home/ray/', 'test'))
    #     fileHandler.setFormatter(logFormatter)
    #     rootLogger.addHandler(fileHandler)
    if len(rootLogger.handlers) != 0:
        return rootLogger
    consoleHandler = logging.StreamHandler(sys.stdout)
    consoleHandler.setFormatter(logFormatter)
    rootLogger.addHandler(consoleHandler)
    if not DISABLE_MONGO:
        rootLogger.addHandler(MongoDBHandler(name, log_db))
    rootLogger.setLevel(logging.INFO)
    return rootLogger


def create_hyper(hyperparam):
    if '_id' in hyperparam:
        del hyperparam['_id']
    client = MongoClient()
    db = client['Experiment'][hyperparam['HYPER_DB']]
    record = db.find_one(hyperparam)
    if record:
        return record['_id']
    else:
        x = db.insert_one(hyperparam)
        return x.inserted_id
